
Partial Class RIAssessments_AssessmentDetails
    Inherits System.Web.UI.Page

    Public assessmentActivityValue As Cdm.RIDataCore.Assessments.AssessmentActivityValue
    Protected assessment As Cdm.RIDataCore.Assessments.Assessment

    Protected ReadOnly Property AssessmentEditable() As Boolean
        Get
            If assessment IsNot Nothing Then
                Return ((UserAuthorization.HasUpdatePermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.Assessments)) And _
                        (assessment.BudgetId = 0))
            Else
                Return True
            End If
        End Get
    End Property

    Protected ReadOnly Property AssessmentApprovable() As Boolean
        Get
            Return (UserAuthorization.HasUpdatePermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.ApproveAssessments))
        End Get
    End Property

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init

        '*  Query String Values:
        '*  aid = assessmentId
        '*  paid = previousAssessmentId (used to copy latest data to new assessment.

        Try

            If Session("UserMessage") IsNot Nothing Then
                Me.ShowMessage(Session("UserMessage"), Drawing.Color.Navy)
                Session("UserMessage") = Nothing
            End If

            '   This page must be loaded on every postback in order to keep the dynamically loaded usercontrol
            '   templates in the grid and be able to reference their values.

            If CInt(Request.QueryString("aid")) <> 0 Then
                If Not UserAuthorization.HasUpdatePermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.Assessments) Then
                    Me.SaveButton.Attributes.Add("onclick", "javascript: alert('You do not have permission to update an assessment.  Please contact your system administrator'); return false;")
                End If
                Me.LoadAssessment(Page.IsPostBack)
            ElseIf CInt(Request.QueryString("paid")) <> 0 Then
                If Not UserAuthorization.HasInsertPermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.Assessments) Then
                    Me.SaveButton.Attributes.Add("onclick", "javascript: alert('You do not have permission to create a new assessment.  Please contact your system administrator'); return false;")
                End If
                Me.LoadPreviousAssessment(Page.IsPostBack)
            Else
                If Not UserAuthorization.HasInsertPermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.Assessments) Then
                    Me.SaveButton.Attributes.Add("onclick", "javascript: alert('You do not have permission to create a new assessment.  Please contact your system administrator'); return false;")
                End If
                Me.LoadNewAssessment()
            End If

            If Not Page.IsPostBack Then
                Me.ApproveBudgetButton.Enabled = Me.AssessmentApprovable
                If Request.QueryString("aid") <> 0 Then
                    Me.DisplayCalculations()
                End If
            End If

            If Request.QueryString("aid") <> 0 Then
                Dim assessmentEditable As Boolean = Me.AssessmentEditable
                If assessment IsNot Nothing Then
                    If assessment.BudgetId <> 0 Or Not assessmentEditable Then
                        Me.DisableSaveAndApprove()
                    End If
                End If
                If assessment.Submitted Then
                    Me.FuncCharCheckBoxList.Enabled = False
                Else
                    Me.FuncCharCheckBoxList.Enabled = assessmentEditable
                End If
            End If

        Catch ex As Gentle.Common.GentleException

            ' This exception will occur if someone tries to manually put an invalid assessment Id in the query string.
            Me.MessageLabel.Visible = True
            Me.MessageLabel.Text = "Assessment failed to load."

        End Try

    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ' Set up appropriate navigation menu items while on assessments.  This must be done because
        ' assessments is a separate screen and not a view in the multi view in casePersonal.aspx.
        EntityController.SetSubNavTabsAssessments(Me.EditCaseSubNav)

        SetupJavaScript()
    End Sub

    Private Sub SetupJavaScript()
        EntityController.JavaScriptAddChildDiv(Me.PageDiv.ClientID, 40)
        EntityController.JavaScriptSetFixedHeight(40)
    End Sub
    

    Protected Sub DisableSaveAndApprove()

        Me.SaveButton.Enabled = False
        Me.SaveButton.ToolTip = "Assessment has already been approved and is no longer editable."
        Me.ApproveBudgetButton.Enabled = False
        Me.ApproveBudgetButton.ToolTip = "Assessment has already been approved."
        Me.SubmitButton.Enabled = False
        Me.SubmitButton.ToolTip = "Assessment has already been approved."
        
    End Sub

    Protected Sub LoadAssessment(ByVal isPostback As Boolean)
        Dim participantFullName As String = EntityController.GetParticipant().FullName
        ' Load the selected assessment.
        assessment = Cdm.RIDataCore.Assessments.Assessment.Retrieve(CInt(Request.QueryString("aid")))

        Me.HeaderLabel.Text = participantFullName & " Assessment - " & CDate(assessment.AssessmentDate).ToShortDateString
        Me.FuncCharCheckBoxList.DataSource = Cdm.RIDataCore.Assessments.FunctionalCharacteristicDisplay.ListByAssessmentId(CInt(Request.QueryString("aid")), "Description")
        Me.FuncCharCheckBoxList.DataTextField = "Description"
        Me.FuncCharCheckBoxList.DataValueField = "FuncCharId"
        Me.FuncCharCheckBoxList.DataBind()
        If Not isPostback Then
            Me.SelectCheckboxes()
        End If
        Me.AssessmentDateInputControl.Value = assessment.AssessmentDate.ToShortDateString
        Me.BindADLSGrid()
        Me.BindIADLSGrid()

    End Sub

    Protected Sub LoadPreviousAssessment(ByVal isPostback As Boolean)

        ' Load the previous assessment associated with this participant.
        assessment = Cdm.RIDataCore.Assessments.Assessment.Retrieve(CInt(Request.QueryString("paid")))

        Me.FuncCharCheckBoxList.DataSource = Cdm.RIDataCore.Assessments.FunctionalCharacteristicDisplay.ListByAssessmentId(CInt(Request.QueryString("paid")), "Description")
        Me.FuncCharCheckBoxList.DataTextField = "Description"
        Me.FuncCharCheckBoxList.DataValueField = "FuncCharId"
        Me.AssessmentDateInputControl.Value = assessment.AssessmentDate.ToString
        Me.FuncCharCheckBoxList.DataBind()
        If Not isPostback Then
            Me.SelectCheckboxes()
        End If
        Me.BindADLSGrid()
        Me.BindIADLSGrid()

    End Sub

    Protected Sub LoadNewAssessment()
        ' Load the previous assessment associated with this participant so we can populate comments
        Try
            assessment = Cdm.RIDataCore.Assessments.Assessment.Retrieve(CInt(Request.QueryString("paid")))
        Catch ex As Exception
            assessment = Nothing
        End Try


        Dim participantFullName As String = EntityController.GetParticipant().FullName
        Me.HeaderLabel.Text = participantFullName & " Assessment"

        ' This is a brand new assessment with no previous assessment associated with the current participant
        ' so we only need to load up the check box list, the rest is just a blank form.
        Me.FuncCharCheckBoxList.DataSource = Cdm.RIDataCore.LookupTables.LuFunctionalCharacteristic.ListBySort("Description")
        Me.FuncCharCheckBoxList.DataTextField = "Description"
        Me.FuncCharCheckBoxList.DataValueField = "FunctionalCharacteristicId"
        Me.FuncCharCheckBoxList.DataBind()
        Me.AssessmentDateInputControl.Value = System.DateTime.Now.ToShortDateString()
        Me.BindADLSGrid()
        Me.BindIADLSGrid()

    End Sub

    Protected Sub BindADLSGrid()

        Dim assessmentId As Integer
        If Request.QueryString("paid") <> 0 Then
            assessmentId = 0
        Else
            If assessment IsNot Nothing Then
                assessmentId = assessment.AssessmentId
            Else
                assessmentId = 0
            End If
        End If
        Me.AdlsAssessmentActivityGridView.DataSource = Cdm.RIDataCore.Assessments.AssessmentActivityDisplay.ListByAssessmentCategoryId(Cdm.RIDataCore.Assessments.AssessmentCategory.Retrieve("ADLS").AssessmentCategoryId, assessmentId, "Description")
        Me.AdlsAssessmentActivityGridView.DataBind()

    End Sub

    Protected Sub BindIADLSGrid()

        Dim assessmentId As Integer
        If Request.QueryString("paid") <> 0 Then
            assessmentId = 0
        Else
            If assessment IsNot Nothing Then
                assessmentId = assessment.AssessmentId
            Else
                assessmentId = 0
            End If
        End If
        Me.IadlsAssessmentActivityGridView.DataSource = Cdm.RIDataCore.Assessments.AssessmentActivityDisplay.ListByAssessmentCategoryId(Cdm.RIDataCore.Assessments.AssessmentCategory.Retrieve("IADLS").AssessmentCategoryId, assessmentId, "Description")
        Me.IadlsAssessmentActivityGridView.DataBind()

    End Sub

    Protected Sub AssessmentActivityGridView_RowDataBound(ByVal sender As Object, _
                                                          ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) _
                                                          Handles AdlsAssessmentActivityGridView.RowDataBound, _
                                                                  IadlsAssessmentActivityGridView.RowDataBound

        ' Hide columns that are only used for reference.
        e.Row.Cells(5).Style("display") = "none"
        e.Row.Cells(6).Style("display") = "none"
        If Request.QueryString("aid") = 0 Then
            e.Row.Cells(3).Style("display") = "none"
        End If
        
        If e.Row.RowType = DataControlRowType.DataRow Then

            ' Determine if we're retrieving the current assessment or previous assessment.
            If CInt(Request.QueryString("aid")) <> 0 Then
                Try
                    assessmentActivityValue = Cdm.RIDataCore.Assessments.AssessmentActivityValue.Retrieve(CInt(e.Row.Cells(5).Text), CInt(Request.QueryString("aid")))
                Catch ex As Gentle.Common.GentleException
                    assessmentActivityValue = Nothing
                End Try
            ElseIf CInt(Request.QueryString("paid")) <> 0 Then
                Try
                    assessmentActivityValue = Cdm.RIDataCore.Assessments.AssessmentActivityValue.Retrieve(CInt(e.Row.Cells(5).Text), CInt(Request.QueryString("paid")))
                Catch ex As Gentle.Common.GentleException
                    assessmentActivityValue = Nothing
                End Try
            End If

            ' Get a reference to the loaded control and the plus image.
            Dim loadedControlPanel As Panel = CType(e.Row.Cells(4).Controls(1), Panel)
            Dim expansionImageButton As ImageButton = CType(e.Row.Cells(0).Controls(1), ImageButton)
            e.Row.Cells(0).Attributes.Add("onclick", "javascript: ToggleDetailsPanel('" & loadedControlPanel.ClientID & "', '" & expansionImageButton.ClientID & "'); return false;")
            e.Row.Cells(0).Style("cursor") = "pointer"

            Dim ctrlToLoad As Control = Me.Page.LoadControl(e.Row.Cells(6).Text)
            loadedControlPanel.Controls.Add(ctrlToLoad)
            loadedControlPanel.Style("display") = "none"

            If Request.QueryString("aid") <> 0 Then
                Dim budgetLabel As Label = CType(e.Row.Cells(3).FindControl("ActivityBudgetLabel"), Label)
                If budgetLabel IsNot Nothing Then
                    budgetLabel.Text = Me.GetCalculatedBudgetByActivity(CInt(e.Row.Cells(5).Text))
                End If
            End If

            Dim assessmentEditable As Boolean = Me.AssessmentEditable

            Select Case e.Row.Cells(6).Text

                Case "TemplateOne.ascx"

                    ' Cast the loaded control to the class TemplateOne and load the appropriate values.
                    Dim ctrl As RIAssessments_TemplateOne = CType(ctrlToLoad, RIAssessments_TemplateOne)
                    If assessmentActivityValue IsNot Nothing Then
                        With assessmentActivityValue
                            ctrl.LevelOfAssistanceId = .LevelOfAssistanceId
                            ctrl.TimesPerDay = IIf(.TimesPerDay = -1, "", .TimesPerDay.ToString)
                            ctrl.DaysPerWeek = IIf(.DaysPerWeek = -1, "", .DaysPerWeek.ToString)                            
                            ctrl.Comments = .Comments                            
                        End With
                    End If
                    If Request.QueryString("aid") <> 0 Then
                        If Not assessmentEditable Or assessment.Submitted Then
                            ctrl.DisableFields()
                        End If
                    End If

                    ' Display a completed flag in the grid when all fields are filled out.
                    If ctrl.IsCompleted Then
                        CType(e.Row.Cells(1).Controls(1), Image).ImageUrl = "~/images/greencheck.gif"
                        CType(e.Row.Cells(1).Controls(1), Image).AlternateText = "true"
                    Else
                        CType(e.Row.Cells(1).Controls(1), Image).ImageUrl = "~/images/blankcheck.gif"
                        CType(e.Row.Cells(1).Controls(1), Image).AlternateText = "false"
                    End If

                Case "TemplateTwo.ascx"

                        ' Cast the loaded control to the class TemplateTwo and load the appropriate values.
                        Dim ctrl As RIAssessments_TemplateTwo = CType(ctrlToLoad, RIAssessments_TemplateTwo)
                        If assessmentActivityValue IsNot Nothing Then
                            With assessmentActivityValue
                                ctrl.LevelOfAssitanceId = .LevelOfAssistanceId
                                ctrl.NumberOfRooms = IIf(.NumberOfRooms = -1, "", .NumberOfRooms.ToString)
                                ctrl.Comments = .Comments
                            End With
                        End If
                        If Request.QueryString("aid") <> 0 Then
                        If Not assessmentEditable Or assessment.Submitted Then
                            ctrl.DisableFields()
                        End If
                        End If

                        ' Display a completed flag in the grid when all fields are filled out.
                        If ctrl.IsCompleted Then
                            CType(e.Row.Cells(1).Controls(1), Image).ImageUrl = "~/images/greencheck.gif"
                            CType(e.Row.Cells(1).Controls(1), Image).AlternateText = "true"
                        Else
                            CType(e.Row.Cells(1).Controls(1), Image).ImageUrl = "~/images/blankcheck.gif"
                            CType(e.Row.Cells(1).Controls(1), Image).AlternateText = "false"
                        End If

                Case "TemplateThree.ascx"

                        ' Cast the loaded control to the class TemplateThree and load the appropriate values.
                        Dim ctrl As RIAssessments_TemplateThree = CType(ctrlToLoad, RIAssessments_TemplateThree)
                        If assessmentActivityValue IsNot Nothing Then
                            With assessmentActivityValue
                                ctrl.LevelOfAssitanceId = .LevelOfAssistanceId
                                ctrl.NumberOfTasks = IIf(.NumberOfTasks = -1, "", .NumberOfTasks.ToString)
                                ctrl.Comments = .Comments
                            End With
                        End If
                        If Request.QueryString("aid") <> 0 Then
                        If Not assessmentEditable Or assessment.Submitted Then
                            ctrl.DisableFields()
                        End If
                        End If

                        ' Display a completed flag in the grid when all fields are filled out.
                        If ctrl.IsCompleted Then
                            CType(e.Row.Cells(1).Controls(1), Image).ImageUrl = "~/images/greencheck.gif"
                            CType(e.Row.Cells(1).Controls(1), Image).AlternateText = "true"
                        Else
                            CType(e.Row.Cells(1).Controls(1), Image).ImageUrl = "~/images/blankcheck.gif"
                            CType(e.Row.Cells(1).Controls(1), Image).AlternateText = "false"
                        End If

                Case "TemplateFour.ascx"

                        ' Cast the loaded control to the class TemplateFour and load the appropriate values.
                        Dim ctrl As RIAssessments_TemplateFour = CType(ctrlToLoad, RIAssessments_TemplateFour)
                        If assessmentActivityValue IsNot Nothing Then
                            With assessmentActivityValue
                                ctrl.LevelOfAssitanceId = .LevelOfAssistanceId
                                ctrl.Comments = .Comments
                            End With
                        End If
                        If Request.QueryString("aid") <> 0 Then
                        If Not assessmentEditable Or assessment.Submitted Then
                            ctrl.DisableFields()
                        End If
                        End If

                        ' Display a completed flag in the grid when all fields are filled out.
                        If ctrl.IsCompleted Then
                            CType(e.Row.Cells(1).Controls(1), Image).ImageUrl = "~/images/greencheck.gif"
                            CType(e.Row.Cells(1).Controls(1), Image).AlternateText = "true"
                        Else
                            CType(e.Row.Cells(1).Controls(1), Image).ImageUrl = "~/images/blankcheck.gif"
                            CType(e.Row.Cells(1).Controls(1), Image).AlternateText = "false"
                        End If

            End Select

        End If

    End Sub

    Protected Sub SelectCheckboxes()

        ' Check the appropriate check boxes in the check box list.  This does not seem to be a bindable property
        ' of a check box list.
        Dim funcChar As Cdm.RIDataCore.Assessments.FunctionalCharacteristic = Nothing
        For Each item As ListItem In Me.FuncCharCheckBoxList.Items
            funcChar = Cdm.RIDataCore.Assessments.FunctionalCharacteristic.Retrieve(item.Value)
            item.Selected = funcChar.HasNeed
        Next

    End Sub

    Protected Sub SaveButton_Click(ByVal sender As Object, _
                                   ByVal e As System.EventArgs) _
                                   Handles SaveButton.Click

        ' Determine if we're looking for an existing assessment.
        If CInt(Request.QueryString("aid")) <> 0 Then

            If UserAuthorization.HasUpdatePermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.Assessments) Then

                If Me.AssessmentIsEditable Then

                    If assessment.BudgetId <> 0 Then
                        Dim budget As Cdm.DataCore.Budget.Budget = Cdm.DataCore.Budget.Budget.Retrieve(assessment.BudgetId)
                        budget.Remove()
                        Me.ApproveBudgetButton.Enabled = True
                    End If

                    ' Save top level assessment information.
                    assessment.BudgetId = 0
                    assessment.LastModified = UserAuthorization.CurrentUser.LogonId
                    assessment.DateModified = Now
                    assessment.AssessmentDate = CDate(Me.AssessmentDateInputControl.Value)
                    assessment.Persist()

                    ' Save functional characteristic values.
                    Dim funcChar As Cdm.RIDataCore.Assessments.FunctionalCharacteristic = Nothing
                    For Each item As ListItem In Me.FuncCharCheckBoxList.Items
                        funcChar = Cdm.RIDataCore.Assessments.FunctionalCharacteristic.Retrieve(item.Value)
                        funcChar.HasNeed = item.Selected
                        funcChar.LastModified = UserAuthorization.CurrentUser.LogonId
                        funcChar.Persist()
                    Next

                    ' Save the Adls assessment data.
                    Me.SaveGrid(Me.AdlsAssessmentActivityGridView)
                    ' Save the Iadls assessment data.
                    Me.SaveGrid(Me.IadlsAssessmentActivityGridView)

                    Me.ShowMessage("Assessment saved successfully " & Now.ToString, Drawing.Color.Navy)

                Else

                    Me.ShowMessage("This assessment is not editable because there is an associated spending plan.", Drawing.Color.Firebrick)
                    Me.LoadAssessment(False)

                End If

            Else

                Me.ShowMessage("Current user does not have permission to alter assessment data.", Drawing.Color.Firebrick)
                Me.LoadAssessment(False)

            End If

        Else

            ' Create a brand new assessment.
            If UserAuthorization.HasInsertPermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.Assessments) Then

                ' Set up a transaction so that all pieces succeed or non succeed.
                Dim tran As Gentle.Framework.Transaction = New Gentle.Framework.Transaction()

                Try

                    ' Create and save a new top level assessment with a reference to no budget.
                    Dim assessment As New Cdm.RIDataCore.Assessments.Assessment(EntityController.GetParticipant.ParticipantId, _
                                                                                0, _
                                                                                Now(), _
                                                                                Now(), _
                                                                                UserAuthorization.CurrentUser.LogonId, _
                                                                                Cdm.RIDataCore.Assessments.AssessmentCost.GetCost.Cost)
                    assessment.LastModified = UserAuthorization.CurrentUser.LogonId
                    assessment.Persist(tran)

                    ' Save the new ADLS and IADLS assessment data.
                    Me.SaveNewGrid(Me.AdlsAssessmentActivityGridView, tran, assessment.AssessmentId)
                    Me.SaveNewGrid(Me.IadlsAssessmentActivityGridView, tran, assessment.AssessmentId)

                    ' Save the new functional characteristic information.
                    Dim functionalCharacteristic As Cdm.RIDataCore.Assessments.FunctionalCharacteristic
                    Dim funcChar As Cdm.RIDataCore.LookupTables.LuFunctionalCharacteristic
                    Dim hasNeed As Boolean = False
                    For Each funcChar In Cdm.RIDataCore.LookupTables.LuFunctionalCharacteristic.ListAll

                        For Each item As ListItem In Me.FuncCharCheckBoxList.Items
                            If item.Text = funcChar.Description Then
                                hasNeed = item.Selected
                                Exit For
                            End If
                        Next

                        functionalCharacteristic = New Cdm.RIDataCore.Assessments.FunctionalCharacteristic(funcChar.FunctionalCharacteristicId, _
                                                                                                           assessment.AssessmentId, _
                                                                                                           hasNeed)
                        functionalCharacteristic.Persist(tran)
                        hasNeed = False

                    Next

                    Dim participant As Cdm.DataCore.Entities.Participant = Cdm.DataCore.Entities.Participant.Retrieve(EntityController.GetParticipant.ParticipantId)
                    participant.LastAssessmentDate = Now()
                    participant.Persist(tran)

                    ' By this point all necessary pieces of a new assessment have been saved so we can
                    ' commit the transaction.
                    tran.Commit()

                    Session("UserMessage") = "Assessment saved successfully " & Now.ToString

                    ' Redirect to this page with the new assessment Id.
                    Response.Redirect("AssessmentDetails.aspx?aid=" & assessment.AssessmentId & "&paid=0")

                Catch ex As Exception

                    ' All pieces of the new assessment did not save so we need to rollback the transaction and quit.
                    tran.Rollback()
                    Me.ShowMessage("Assessment failed to save.", Drawing.Color.Firebrick)

                End Try

            Else

                Me.ShowMessage("Current user does not have permission to create a new assessment.", Drawing.Color.Firebrick)
                If Request.QueryString("paid") <> 0 Then
                    Me.LoadPreviousAssessment(False)
                Else
                    Me.LoadNewAssessment()
                End If

            End If

        End If

        Me.DisplayCalculations()

    End Sub

    Protected Function AssessmentIsEditable() As Boolean

        ' Determines if an assessment is editable.
        ' 1. Assessments with budgetId = 0 are editable.
        ' 2. Assessments with a budgetId and no spending plan are editable.
        ' 3. Assessments with a budgetId and an associated spending plan are not editable.

        Dim isEditableReturnValue As Boolean = True
        If assessment IsNot Nothing Then

            If assessment.BudgetId = 0 Then
                isEditableReturnValue = True
            Else

                Try

                    Dim budget As Cdm.DataCore.Budget.Budget = Cdm.DataCore.Budget.Budget.Retrieve(assessment.BudgetId)
                    isEditableReturnValue = Not Me.SpendingPlanExists(budget.BudgetId)

                Catch ex As Gentle.Common.GentleException

                    isEditableReturnValue = True

                End Try

            End If

        Else
            isEditableReturnValue = False
        End If

        Return isEditableReturnValue

    End Function

    Protected Function SpendingPlanExists(ByVal budgetId As Integer) As Boolean

        Dim spendingPlans As System.Collections.Generic.List(Of Cdm.DataCore.Budget.SpendingPlan)
        Try
            spendingPlans = Cdm.DataCore.Budget.SpendingPlan.ListByBudgetId(budgetId)
            If spendingPlans.Count > 0 Then
                Return True
            Else
                Return False
            End If
        Catch ex As Gentle.Common.GentleException
            Return False
        End Try

    End Function

    Protected Sub CancelButton_Click(ByVal sender As Object, _
                                     ByVal e As System.EventArgs) _
                                     Handles CancelButton.Click

        ' Go back to the list.
        Response.Redirect("Assessments.aspx")

    End Sub

    Protected Sub SaveNewGrid(ByVal grid As GridView, _
                              ByVal tran As Gentle.Framework.Transaction, _
                              ByVal assessmentId As Integer)

        Dim activityValue As Cdm.RIDataCore.Assessments.AssessmentActivityValue
        Dim activityControl As Control

        For Each row As GridViewRow In grid.Rows

            activityControl = CType(row.Cells(4).Controls(1), Panel).Controls(0)

            Dim levelOfAssistId As Integer
            Dim timesPerDay As Double
            Dim daysPerWeek As Integer
            Dim numberOfRooms As Integer
            Dim numberOfTasks As Integer
            Dim comments As String

            Dim levelOfAssistDropDownList As DropDownList = CType(activityControl.FindControl("LevelOfAssistanceDropDownList"), DropDownList)
            If levelOfAssistDropDownList IsNot Nothing Then
                levelOfAssistId = levelOfAssistDropDownList.SelectedValue
            Else
                levelOfAssistId = 1
            End If

            Dim timesPerDayTextBox As TextBox = CType(activityControl.FindControl("TimesPerDayTextBox"), TextBox)
            If timesPerDayTextBox IsNot Nothing Then
                If IsNumeric(timesPerDayTextBox.Text) Then
                    timesPerDay = timesPerDayTextBox.Text
                Else
                    timesPerDay = -1
                End If
            Else
                timesPerDay = -1
            End If

            Dim daysPerWeekTextBox As TextBox = CType(activityControl.FindControl("DaysPerWeekTextBox"), TextBox)
            If daysPerWeekTextBox IsNot Nothing Then
                If IsNumeric(daysPerWeekTextBox.Text) Then
                    daysPerWeek = daysPerWeekTextBox.Text
                Else
                    daysPerWeek = -1
                End If
            Else
                daysPerWeek = -1
            End If

            Dim numberOfRoomsTextBox As TextBox = CType(activityControl.FindControl("NumberOfRoomsTextBox"), TextBox)
            If numberOfRoomsTextBox IsNot Nothing Then
                If IsNumeric(numberOfRoomsTextBox.Text) Then
                    numberOfRooms = numberOfRoomsTextBox.Text
                Else
                    numberOfRooms = -1
                End If
            Else
                numberOfRooms = -1
            End If

            Dim numberOfTasksTextBox As TextBox = CType(activityControl.FindControl("NumberOfTasksTextBox"), TextBox)
            If numberOfTasksTextBox IsNot Nothing Then
                If IsNumeric(numberOfTasksTextBox.Text) Then
                    numberOfTasks = numberOfTasksTextBox.Text
                Else
                    numberOfTasks = -1
                End If
            Else
                numberOfTasks = -1
            End If

            Dim commentsTextBox As TextBox = CType(activityControl.FindControl("CommentsTextBox"), TextBox)
            If commentsTextBox IsNot Nothing Then
                comments = commentsTextBox.Text
            Else
                comments = ""
            End If

            activityValue = New Cdm.RIDataCore.Assessments.AssessmentActivityValue(CInt(row.Cells(5).Text), _
                                                                                   assessmentId, _
                                                                                   levelOfAssistId, _
                                                                                   timesPerDay, _
                                                                                   daysPerWeek, _
                                                                                   comments, _
                                                                                   numberOfRooms, _
                                                                                   numberOfTasks, _
                                                                                   UserAuthorization.CurrentUser.LogonId)

            activityValue.Persist(tran)

        Next

    End Sub

    Protected Sub SaveGrid(ByVal grid As GridView)

        Dim activityValue As Cdm.RIDataCore.Assessments.AssessmentActivityValue
        Dim activityControl As Control

        For Each row As GridViewRow In grid.Rows

            Try
                activityValue = Cdm.RIDataCore.Assessments.AssessmentActivityValue.Retrieve(CInt(row.Cells(5).Text), CInt(Request.QueryString("aid")))
            Catch ex As Gentle.Common.GentleException
                activityValue = New Cdm.RIDataCore.Assessments.AssessmentActivityValue()
                activityValue.AssessmentId = assessment.AssessmentId
                activityValue.AssessmentActivityId = CInt(row.Cells(5).Text)
            End Try

            If activityValue IsNot Nothing Then

                activityControl = CType(row.Cells(4).Controls(1), Panel).Controls(0)

                Dim levelOfAssistDropDownList As DropDownList = CType(activityControl.FindControl("LevelOfAssistanceDropDownList"), DropDownList)
                Dim timesPerDayTextBox As TextBox = CType(activityControl.FindControl("TimesPerDayTextBox"), TextBox)
                Dim daysPerWeekTextBox As TextBox = CType(activityControl.FindControl("DaysPerWeekTextBox"), TextBox)
                Dim numberOfRoomsTextBox As TextBox = CType(activityControl.FindControl("NumberOfRoomsTextBox"), TextBox)
                Dim numberOfTasksTextBox As TextBox = CType(activityControl.FindControl("NumberOfTasksTextBox"), TextBox)
                Dim commentsTextBox As TextBox = CType(activityControl.FindControl("CommentsTextBox"), TextBox)

                With activityValue

                    If levelOfAssistDropDownList IsNot Nothing Then
                        .LevelOfAssistanceId = levelOfAssistDropDownList.SelectedValue
                    End If

                    If timesPerDayTextBox IsNot Nothing Then
                        If levelOfAssistDropDownList.SelectedItem.ToString <> "Not Applicable" Then
                            If IsNumeric(timesPerDayTextBox.Text) Then
                                .TimesPerDay = timesPerDayTextBox.Text
                            Else
                                .TimesPerDay = -1
                            End If
                        Else
                            .TimesPerDay = -1
                        End If
                    End If

                    If daysPerWeekTextBox IsNot Nothing Then
                        If levelOfAssistDropDownList.SelectedItem.ToString <> "Not Applicable" Then
                            If IsNumeric(daysPerWeekTextBox.Text) Then
                                .DaysPerWeek = daysPerWeekTextBox.Text
                            Else
                                .DaysPerWeek = -1
                            End If
                        Else
                            .DaysPerWeek = -1
                        End If
                    End If

                    If numberOfRoomsTextBox IsNot Nothing Then
                        If levelOfAssistDropDownList.SelectedItem.ToString <> "Not Applicable" Then
                            If IsNumeric(numberOfRoomsTextBox.Text) Then
                                .NumberOfRooms = numberOfRoomsTextBox.Text
                            Else
                                .NumberOfRooms = -1
                            End If
                        Else
                            .NumberOfRooms = -1
                        End If
                    End If

                    If numberOfTasksTextBox IsNot Nothing Then
                        If levelOfAssistDropDownList.SelectedItem.ToString <> "Not Applicable" Then
                            If IsNumeric(numberOfTasksTextBox.Text) Then
                                .NumberOfTasks = numberOfTasksTextBox.Text
                            Else
                                .NumberOfTasks = -1
                            End If
                        Else
                            .NumberOfTasks = -1
                        End If
                    End If

                    If commentsTextBox IsNot Nothing Then
                        If levelOfAssistDropDownList.SelectedItem.ToString <> "Not Applicable" Then
                            .Comments = commentsTextBox.Text
                        End If
                    End If

                    .LastModified = UserAuthorization.CurrentUser.LogonId

                End With

                activityValue.Persist()

            End If

        Next

        If grid.ID.IndexOf("Iadls") <> -1 Then
            Me.BindIADLSGrid()
        Else
            Me.BindADLSGrid()
        End If

    End Sub

    Private Sub ShowMessage(ByVal message As String, _
                            ByVal color As System.Drawing.Color)

        Me.MessageLabel.ForeColor = color
        Me.MessageLabel.Text = message
        Me.MessageLabel.Visible = True

    End Sub

    Protected Sub ApproveBudgetButton_Click(ByVal sender As Object, _
                                            ByVal e As System.EventArgs) _
                                            Handles ApproveBudgetButton.Click

        Me.EffectiveDateCalendar.VisibleDate = Now
        Me.EffectiveDateCalendar.SelectedDate = Now

        Me.ExpirationDateCalendar.VisibleDate = DateAdd(DateInterval.Year, 1, Now)
        Me.ExpirationDateCalendar.SelectedDate = DateAdd(DateInterval.Year, 1, Now)

        Me.ActionPanel.Visible = False
        Me.GridContentPanel.Visible = False
        Me.CreateBudgetPanel.Visible = True
        Me.BudgetAmountTextBox.Text = Me.GetCalculatedBudget

    End Sub

    Protected Function GetCalculatedBudget() As String

        Dim total As Double = 0.0
        If assessment IsNot Nothing Then

            Dim activityBudget As Cdm.RIDataCore.Assessments.AssessmentActivityBudget
            For Each activityBudget In Cdm.RIDataCore.Assessments.AssessmentActivityBudget.ListByAssessmentId(assessment.AssessmentId)
                total += CDbl(activityBudget.BudgetCalculation)
            Next

        End If

        Return Format(total, "$###,###,##0.00")

    End Function

    Protected Function GetCalculatedBudgetByActivity(ByVal activityId As Integer) As String

        If assessment IsNot Nothing Then

            Dim activityBudget As Cdm.RIDataCore.Assessments.AssessmentActivityBudget
            For Each activityBudget In Cdm.RIDataCore.Assessments.AssessmentActivityBudget.ListByAssessmentId(assessment.AssessmentId)
                If activityBudget.AssessmentActivityId = activityId Then
                    Return Format(CDbl(activityBudget.BudgetCalculation), "$###,###,##0.00")
                End If
            Next

        End If

        Return Nothing

    End Function

    Protected Function GetApprovedBudget() As String

        Dim total As Double = 0.0
        If assessment IsNot Nothing Then
            If assessment.BudgetId <> 0 Then
                Dim budget As Cdm.DataCore.Budget.Budget = Cdm.DataCore.Budget.Budget.Retrieve(assessment.BudgetId)
                total = budget.BudgetAmount
            End If
        End If
        Return Format(total, "$###,###,##0.00")

    End Function

    Protected Function CreateBudget(ByVal effectiveDate As DateTime, ByVal expirationDate As DateTime) As Boolean

        If assessment IsNot Nothing Then

            Try
                If Not IsDate(effectiveDate) Or Not IsDate(expirationDate) Then
                    ShowMessage("Please select valid effective date and expiration date.", Drawing.Color.Red)
                    Return False
                End If
                If expirationDate <= effectiveDate Then
                    ShowMessage("Expiration Date must be later than Effective Date.", Drawing.Color.Red)
                    Return False
                End If

                Dim budgetString As String = Me.BudgetAmountTextBox.Text.Substring(1)
                Dim budgetAmount As Double
                If IsNumeric(budgetString) And effectiveDate.Year > 1900 Then

                    budgetAmount = CDbl(budgetString)

                    Dim budget As Cdm.DataCore.Budget.Budget
                    budget = New Cdm.DataCore.Budget.Budget("", _
                                                            budgetAmount, _
                                                            EntityController.GetParticipant.ParticipantId, _
                                                            UserAuthorization.CurrentUser.LogonId, _
                                                            Now(), _
                                                            effectiveDate)
                    budget.ExpirationDate = expirationDate
                    budget.BudgetPeriodId = Cdm.DataCore.LookupTables.LuBudgetPeriod.RetrieveDefaultBudgetPeriodId()
                    'budget.SetExpirationDates(EntityController.GetParticipant.ParticipantId, effectiveDate.Subtract(System.TimeSpan.FromDays(1)))
                    budget.Persist()
                    If Not String.IsNullOrEmpty(budget.ErrorMessage) Then
                        ShowMessage("Can not save budget: " + budget.ErrorMessage, Drawing.Color.Red)
                        Return False
                    End If
                    assessment.BudgetId = budget.BudgetId
                    assessment.Persist()

                    Me.DisplayCalculations()

                    Return True

                Else

                    Return False

                End If

            Catch gentileEx As Gentle.Common.GentleException

                Return False

            Catch ex As Exception

                Return False

            End Try

        End If

    End Function

    Protected Sub ApproveButton_Click(ByVal sender As Object, _
                                      ByVal e As System.EventArgs) _
                                      Handles ApproveButton.Click

        If Me.CreateBudget(Me.EffectiveDateCalendar.SelectedDate, Me.ExpirationDateCalendar.SelectedDate) Then

            Me.ApproveBudgetButton.Enabled = False
            Me.ActionPanel.Visible = True
            Me.GridContentPanel.Visible = True
            Me.CreateBudgetPanel.Visible = False
            Me.DisableSaveAndApprove()
            Me.BindADLSGrid()
            Me.BindIADLSGrid()
            Me.FuncCharCheckBoxList.Enabled = AssessmentEditable
            ShowMessage("Budget Approved,", Drawing.Color.Blue)
        Else

            Me.ApproveBudgetButton.Enabled = True
            Me.ActionPanel.Visible = True
            Me.GridContentPanel.Visible = True
            Me.CreateBudgetPanel.Visible = False
            Me.BindADLSGrid()
            Me.BindIADLSGrid()
            Me.FuncCharCheckBoxList.Enabled = AssessmentEditable
        End If

    End Sub

    Protected Sub CancelApproveButton_Click(ByVal sender As Object, _
                                            ByVal e As System.EventArgs) _
                                            Handles CancelApproveButton.Click

        Me.ActionPanel.Visible = True
        Me.GridContentPanel.Visible = True
        Me.CreateBudgetPanel.Visible = False

    End Sub

    Protected Sub DisplayCalculations()

        Me.CalculatedBudgetValueLabel.Text = Me.GetCalculatedBudget
        Me.ApprovedBudgetValueLabel.Text = Me.GetApprovedBudget
        If UserAuthorization.HasUpdatePermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.ApproveAssessments) Then
            If assessment IsNot Nothing Then
                Me.ApproveBudgetButton.Enabled = ((assessment.BudgetId = 0) And (Request.QueryString("aid") <> 0))
            End If
            Me.ApprovedBudgetPanel.Visible = True
            Me.ApproveButton.Attributes.Add("onclick", "javascript: return confirm('Are you sure you want to approve this assessment.');")
        Else
            'Me.ApprovedBudgetPanel.Visible = False
            Me.ApproveBudgetButton.Enabled = False
        End If

    End Sub

    Protected Sub ViewPrintableCopyButton_Click(ByVal sender As Object, _
                                                ByVal e As System.EventArgs) _
                                                Handles ViewPrintableCopyButton.Click

        If assessment IsNot Nothing Then
            Response.Redirect("PrintableCopy.aspx?aid=" & assessment.AssessmentId)
        Else
            Me.ShowMessage("There are no saved assessments to view.", Drawing.Color.Firebrick)
        End If

    End Sub

    Protected Sub EditCaseSubNav_ChangeMenu(ByVal sender As Object, _
                                            ByVal e As System.EventArgs) _
                                            Handles EditCaseSubNav.ChangeMenu

        ' Handle the change menu event in order to redirect back to casePersonal.aspx in the correct location.
        EntityController.ReturnToCasePersonalPage(Me.EditCaseSubNav)

    End Sub
    
    Protected Sub SubmitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SubmitButton.Click

        'Set Submitted property to true - controls whether fields are editable or not
        assessment.Submitted = True

        ' Determine if we're looking for an existing assessment.
        If CInt(Request.QueryString("aid")) <> 0 Then

            If UserAuthorization.HasUpdatePermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.Assessments) Then

                If Me.AssessmentIsEditable Then

                    If assessment.BudgetId <> 0 Then
                        Dim budget As Cdm.DataCore.Budget.Budget = Cdm.DataCore.Budget.Budget.Retrieve(assessment.BudgetId)
                        budget.Remove()
                        Me.ApproveBudgetButton.Enabled = True
                    End If

                    ' Save top level assessment information.
                    assessment.BudgetId = 0
                    assessment.LastModified = UserAuthorization.CurrentUser.LogonId
                    assessment.DateModified = Now
                    assessment.AssessmentDate = CDate(Me.AssessmentDateInputControl.Value)
                    assessment.Persist()

                    ' Save functional characteristic values.
                    Dim funcChar As Cdm.RIDataCore.Assessments.FunctionalCharacteristic = Nothing
                    For Each item As ListItem In Me.FuncCharCheckBoxList.Items
                        funcChar = Cdm.RIDataCore.Assessments.FunctionalCharacteristic.Retrieve(item.Value)
                        funcChar.HasNeed = item.Selected
                        funcChar.LastModified = UserAuthorization.CurrentUser.LogonId
                        funcChar.Persist()
                    Next

                    ' Save the Adls assessment data.
                    Me.SaveGrid(Me.AdlsAssessmentActivityGridView)
                    ' Save the Iadls assessment data.
                    Me.SaveGrid(Me.IadlsAssessmentActivityGridView)

                    Me.ShowMessage("Assessment saved successfully " & Now.ToString, Drawing.Color.Navy)

                Else

                    Me.ShowMessage("This assessment is not editable because there is an associated spending plan.", Drawing.Color.Firebrick)
                    Me.LoadAssessment(False)

                End If

            Else

                Me.ShowMessage("Current user does not have permission to alter assessment data.", Drawing.Color.Firebrick)
                Me.LoadAssessment(False)
                assessment.Submitted = False

            End If

        Else

            ' Create a brand new assessment.
            If UserAuthorization.HasInsertPermission(Cdm.DataCore.UserSecurity.Permission.PermissionType.Assessments) Then

                ' Set up a transaction so that all pieces succeed or non succeed.
                Dim tran As Gentle.Framework.Transaction = New Gentle.Framework.Transaction()

                Try

                    ' Create and save a new top level assessment with a reference to no budget.
                    Dim assessment As New Cdm.RIDataCore.Assessments.Assessment(EntityController.GetParticipant.ParticipantId, _
                                                                                0, _
                                                                                Now(), _
                                                                                Now(), _
                                                                                UserAuthorization.CurrentUser.LogonId, _
                                                                                Cdm.RIDataCore.Assessments.AssessmentCost.GetCost.Cost)
                    assessment.LastModified = UserAuthorization.CurrentUser.LogonId
                    assessment.Persist(tran)

                    ' Save the new ADLS and IADLS assessment data.
                    Me.SaveNewGrid(Me.AdlsAssessmentActivityGridView, tran, assessment.AssessmentId)
                    Me.SaveNewGrid(Me.IadlsAssessmentActivityGridView, tran, assessment.AssessmentId)

                    ' Save the new functional characteristic information.
                    Dim functionalCharacteristic As Cdm.RIDataCore.Assessments.FunctionalCharacteristic
                    Dim funcChar As Cdm.RIDataCore.LookupTables.LuFunctionalCharacteristic
                    Dim hasNeed As Boolean = False
                    For Each funcChar In Cdm.RIDataCore.LookupTables.LuFunctionalCharacteristic.ListAll

                        For Each item As ListItem In Me.FuncCharCheckBoxList.Items
                            If item.Text = funcChar.Description Then
                                hasNeed = item.Selected
                                Exit For
                            End If
                        Next

                        functionalCharacteristic = New Cdm.RIDataCore.Assessments.FunctionalCharacteristic(funcChar.FunctionalCharacteristicId, _
                                                                                                           assessment.AssessmentId, _
                                                                                                           hasNeed)
                        functionalCharacteristic.Persist(tran)
                        hasNeed = False

                    Next

                    Dim participant As Cdm.DataCore.Entities.Participant = Cdm.DataCore.Entities.Participant.Retrieve(EntityController.GetParticipant.ParticipantId)
                    participant.LastAssessmentDate = Now()
                    participant.Persist(tran)

                    ' By this point all necessary pieces of a new assessment have been saved so we can
                    ' commit the transaction.
                    tran.Commit()

                    Session("UserMessage") = "Assessment saved successfully " & Now.ToString

                    ' Redirect to this page with the new assessment Id.
                    Response.Redirect("AssessmentDetails.aspx?aid=" & assessment.AssessmentId & "&paid=0")

                Catch ex As Exception

                    ' All pieces of the new assessment did not save so we need to rollback the transaction and quit.
                    tran.Rollback()
                    Me.ShowMessage("Assessment failed to save.", Drawing.Color.Firebrick)
                    assessment.Submitted = False

                End Try

            Else

                'assessment.Submitted = False
                Me.ShowMessage("Current user does not have permission to create a new assessment.", Drawing.Color.Firebrick)
                If Request.QueryString("paid") <> 0 Then
                    Me.LoadPreviousAssessment(False)
                Else
                    Me.LoadNewAssessment()
                End If

            End If

        End If

        Me.DisplayCalculations()

        Me.DisableSaveAndApprove()
 
        'Add code for send notification - check if this is done in Persist method
    End Sub
End Class
